package com.ruoyi.web.controller.h5;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.H5User;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.User;
import com.ruoyi.system.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.CustomerLoginService;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户Controller
 * 
 * @author ruoyi
 * @date 2025-06-11
 */
@RestController
@Api("h5端用户信息")
@RequestMapping("/h5")
public class H5UserController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private CustomerLoginService loginService;
    @Autowired
    private TokenService tokenService;


    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    
    @ApiOperation("注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody User user)
    {
        String msg = userService.rigister(user);
        return AjaxResult.success(msg);
    }
    
    /** */
    @GetMapping("/getInfo")
    public AjaxResult getInfo(){
        
        LoginUser loginUser = SecurityUtils.getLoginUser();
        User user = userService.selectUserById(loginUser.getUserId());
        H5User h5User = new H5User();
        h5User.setId(user.getId());
        h5User.setUsername(user.getUsername());
        h5User.setPassword(user.getPassword());
        tokenService.refreshToken(loginUser);
        return AjaxResult.success(user);
    }

    /**
     * 查询用户列表
     */
    @ApiOperation("获取用户列表")
    @GetMapping("/user/list")
    public AjaxResult list(User user) {
        // startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        
        H5User sysUser = loginUser.getH5User();
        if(sysUser.getTop().equals(0L)){
            user.setTop(sysUser.getId());
        }else{
            user.setTop(sysUser.getTop());
        }
        List<User> list = userService.selectUserList(user);
        return AjaxResult.success(list);
    }

    @ApiOperation("获取企业用户")
    @GetMapping("/selectUsersByTop")
    public AjaxResult selectUsersByTop() {
        return success(userService.selectUsersByTop());
    }

    /**
     * 获取用户详细信息
     */
    @ApiOperation("获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping(value = "/user/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(userService.selectUserById(id));
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User", paramType = "body", dataTypeClass = User.class)
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping("/user/add")
    public AjaxResult add(@RequestBody User user) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        H5User sysUser = loginUser.getH5User();
        if(sysUser.getTop().equals(0L)){
            user.setTop(sysUser.getId());
        }else{
            user.setTop(sysUser.getTop());
        }
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User", paramType = "body", dataTypeClass = User.class)
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping("/user/edit")
    public AjaxResult edit(@RequestBody User user) {

        // if (StringUtils.isNotEmpty(user.getPassword())) {
        //     String password = user.getPassword();
        //     String encrty = SecurityUtils.encryptPassword(password)
        //     user.setPassword(encrty);
        // }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "ids", value = "用户ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/user/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 通用上传请求（单个）
     */
    @SuppressWarnings("null")
    @Anonymous
    @PostMapping("/upload")
    @ApiOperation("上传文件")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "MultipartFile", paramType = "form")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 检查文件类型
            String fileType = file.getContentType();
            if (!fileType.startsWith("image/")) {
                return AjaxResult.error("只允许上传图片文件");
            }

            // 检查文件大小（例如限制为5MB）
            long fileSize = file.getSize();
            if (fileSize > 5 * 1024 * 1024) {
                return AjaxResult.error("文件大小不能超过5MB");
            }

            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
